package com.ktv.web.controller.com.ktv.web.handler.impl;

import com.ktv.web.controller.com.ktv.web.handler.RequestHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Date;

/**
 * Created by ivey.yuan on 2016/3/2.
 */
@ServerEndpoint("/webSocket")
public class SocketRequestHandler implements RequestHandler{


    private Session session;

    @OnOpen
    public void onOpen(Session session){
        this.session = session;
    }

    @OnClose
    public void onClose(){
        System.out.println("有一连接关闭！");
    }


    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("来自客户端的消息:" + message);
        try {
            sendMessage(new Date().toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("发生错误");
        error.printStackTrace();
    }

  
    public void sendMessage(String message) throws IOException{
        this.session.getBasicRemote().sendText(message);
    }
    @Override
    public String handle(HttpServletRequest request, HttpServletResponse response) throws IOException {
        return new Date().toString();
    }
}
